package ClientLogic;



import java.io.IOException;



import ocsf.client.*;


/**
 * This class responsible for connecting between the Client GUI to the server.
 * it is actually a messenger between the two.
 * 
 
 * @author Andrey
 * @author Igor
 */

public class ClientHandle extends AbstractClient {
	
	
	/**
	 * message 
	 */
	public Object message=null;
	
	/**
	 * The constructor connects to the server
	 * @param host  ip of the Server
	 * @param port  port the server listens to
	 * @throws IOException
	 */
	public ClientHandle(String host,int port) throws IOException
	{
		super(host,port);
		openConnection();
		
	}
	

	/**
	 * This method must be synchronized, it is always waiting to get an Object and
	 * when it does it notifies other methods that waits for the Object to arrive.
	 * 
	 */
	@Override
	public synchronized void handleMessageFromServer(Object msg) {
		// TODO Auto-generated method stub
		while (msg==null)
			try {
				wait();
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			this.message=msg;
			notifyAll();

					try {
			openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	

	/**
	 * This method is responsible for sending messages to the server .
	 * 
	 */
	
	public  void HandleMessageFromGUI(Object msg) throws IOException
	{
		sendToServer(msg);
	}
	
	
	
	/**
	 * Method waits for a message to arrive, when the method handleMessageFromServer gets a message
	 * it wakes this method and then this method delivers the message
	 * @return a message from the server
	 * @throws IOException
	 */
	
	public synchronized Object GetMessage() throws IOException
	{
		try {
				wait();

				
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this.message;
	}
	
	
	/**
	 * This method is responsible for recovering messages .
	 * 
	 */
	public synchronized Object SpecialGetMessage()
	{
		return this.message;
	}
}